#!/usr/bin/env python3
"""
性能优化和问题修复脚本
解决程序运行慢和plotly报错问题
"""

import sys
import os
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

def check_plotly_installation():
    """检查plotly安装情况"""
    print("🔍 检查Plotly安装情况...")
    
    try:
        import plotly
        print(f"✅ Plotly版本: {plotly.__version__}")
        
        # 检查是否有kaleido（用于静态图片导出）
        try:
            import kaleido
            print(f"✅ Kaleido版本: {kaleido.__version__}")
        except ImportError:
            print("⚠️ Kaleido未安装（可选，用于图片导出）")
        
        return True
    except ImportError:
        print("❌ Plotly未安装")
        return False

def check_dependencies():
    """检查关键依赖"""
    print("\n📦 检查关键依赖...")
    
    dependencies = {
        'plotly': '图表库',
        'pandas': '数据处理',
        'numpy': '数值计算',
        'fastapi': 'Web框架',
        'uvicorn': 'ASGI服务器',
        'akshare': '股票数据',
        'redis': '缓存系统'
    }
    
    missing = []
    for package, desc in dependencies.items():
        try:
            __import__(package)
            print(f"✅ {package} - {desc}")
        except ImportError:
            print(f"❌ {package} - {desc} (缺失)")
            missing.append(package)
    
    return missing

def optimize_plotly_config():
    """优化Plotly配置"""
    print("\n🔧 优化Plotly配置...")
    
    # 创建优化的plotly配置文件
    config_content = '''
// Plotly优化配置
window.PlotlyConfig = {
    // 减少内存使用
    plotGlPixelRatio: 1,
    
    // 优化渲染性能
    responsive: true,
    displayModeBar: false,
    
    // 减少动画
    staticPlot: false,
    
    // 配置选项
    modeBarButtonsToRemove: [
        'pan2d', 'lasso2d', 'select2d', 'autoScale2d',
        'hoverClosestCartesian', 'hoverCompareCartesian'
    ],
    
    // 显示配置
    displaylogo: false,
    
    // 性能优化
    editable: false,
    scrollZoom: false
};

// 全局Plotly配置
if (typeof Plotly !== 'undefined') {
    Plotly.setPlotConfig({
        plotGlPixelRatio: 1,
        mapboxAccessToken: null
    });
}
'''
    
    # 保存配置文件
    os.makedirs("frontend/static", exist_ok=True)
    with open("frontend/static/plotly-config.js", "w", encoding="utf-8") as f:
        f.write(config_content)
    
    print("✅ Plotly配置文件已创建")

def create_cdn_fallback():
    """创建CDN备用方案"""
    print("\n🌐 创建CDN备用方案...")
    
    fallback_script = '''
<!-- Plotly CDN with fallback -->
<script>
    // 检查Plotly是否加载成功
    function checkPlotly() {
        if (typeof Plotly === 'undefined') {
            console.warn('Plotly CDN加载失败，尝试备用CDN...');
            
            // 备用CDN列表
            const fallbackCDNs = [
                'https://cdn.jsdelivr.net/npm/plotly.js@latest/dist/plotly.min.js',
                'https://unpkg.com/plotly.js@latest/dist/plotly.min.js',
                'https://cdnjs.cloudflare.com/ajax/libs/plotly.js/2.26.0/plotly.min.js'
            ];
            
            let currentIndex = 0;
            
            function loadFallback() {
                if (currentIndex >= fallbackCDNs.length) {
                    console.error('所有Plotly CDN都加载失败');
                    showPlotlyError();
                    return;
                }
                
                const script = document.createElement('script');
                script.src = fallbackCDNs[currentIndex];
                script.onload = function() {
                    console.log('Plotly备用CDN加载成功:', fallbackCDNs[currentIndex]);
                };
                script.onerror = function() {
                    console.warn('备用CDN失败:', fallbackCDNs[currentIndex]);
                    currentIndex++;
                    loadFallback();
                };
                document.head.appendChild(script);
            }
            
            loadFallback();
        }
    }
    
    // 显示Plotly错误信息
    function showPlotlyError() {
        const chartDivs = document.querySelectorAll('#chart, #marketChart');
        chartDivs.forEach(div => {
            if (div) {
                div.innerHTML = `
                    <div style="padding: 20px; text-align: center; border: 2px dashed #ccc; border-radius: 8px;">
                        <h3 style="color: #e74c3c;">📊 图表加载失败</h3>
                        <p>Plotly库加载失败，可能的原因：</p>
                        <ul style="text-align: left; display: inline-block;">
                            <li>网络连接问题</li>
                            <li>CDN服务不可用</li>
                            <li>浏览器兼容性问题</li>
                        </ul>
                        <p><strong>解决方案：</strong></p>
                        <ol style="text-align: left; display: inline-block;">
                            <li>检查网络连接</li>
                            <li>刷新页面重试</li>
                            <li>使用现代浏览器</li>
                        </ol>
                    </div>
                `;
            }
        });
    }
    
    // 页面加载完成后检查
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(checkPlotly, 2000);
    });
</script>
'''
    
    with open("frontend/static/plotly-fallback.html", "w", encoding="utf-8") as f:
        f.write(fallback_script)
    
    print("✅ CDN备用方案已创建")

def optimize_data_processing():
    """优化数据处理"""
    print("\n⚡ 优化数据处理...")
    
    # 创建数据处理优化脚本
    optimization_code = '''
# 数据处理优化建议

## 1. 减少数据量
- 限制图表数据点数量（最多100个点）
- 使用数据采样和聚合
- 分页加载大量数据

## 2. 缓存策略
- 使用Redis缓存图表数据
- 客户端缓存静态数据
- 避免重复计算

## 3. 异步处理
- 使用异步数据获取
- 后台预处理数据
- 分批加载数据

## 4. 前端优化
- 延迟加载图表
- 使用虚拟滚动
- 减少DOM操作
'''
    
    with open("PERFORMANCE_TIPS.md", "w", encoding="utf-8") as f:
        f.write(optimization_code)
    
    print("✅ 性能优化建议已创建")

def install_missing_packages(missing_packages):
    """安装缺失的包"""
    if not missing_packages:
        return True
    
    print(f"\n📥 安装缺失的包: {', '.join(missing_packages)}")
    
    try:
        import subprocess
        
        # 使用国内镜像源加速安装
        cmd = [
            sys.executable, "-m", "pip", "install",
            "-i", "https://pypi.tuna.tsinghua.edu.cn/simple/"
        ] + missing_packages
        
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            print("✅ 包安装成功")
            return True
        else:
            print(f"❌ 包安装失败: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"❌ 安装过程出错: {e}")
        return False

def create_performance_test():
    """创建性能测试脚本"""
    print("\n🧪 创建性能测试脚本...")
    
    test_code = '''#!/usr/bin/env python3
"""
性能测试脚本
"""

import time
import requests
import sys
import os

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

def test_api_performance():
    """测试API性能"""
    base_url = "http://localhost:8000"
    
    tests = [
        ("/health", "健康检查"),
        ("/api/stock/stocks", "股票列表"),
        ("/api/realtime/status", "实时服务状态"),
        ("/api/market/status", "大盘服务状态")
    ]
    
    print("🚀 API性能测试")
    print("=" * 50)
    
    for endpoint, name in tests:
        try:
            start_time = time.time()
            response = requests.get(f"{base_url}{endpoint}", timeout=10)
            end_time = time.time()
            
            duration = (end_time - start_time) * 1000
            status = "✅" if response.status_code == 200 else "❌"
            
            print(f"{status} {name}: {duration:.2f}ms")
            
        except Exception as e:
            print(f"❌ {name}: 错误 - {e}")

if __name__ == "__main__":
    test_api_performance()
'''
    
    with open("test_performance.py", "w", encoding="utf-8") as f:
        f.write(test_code)
    
    print("✅ 性能测试脚本已创建")

def main():
    """主函数"""
    print("🔧 性能优化和问题修复工具")
    print("=" * 50)
    
    # 1. 检查Plotly
    if not check_plotly_installation():
        print("\n❌ Plotly未安装，正在安装...")
        if not install_missing_packages(['plotly']):
            print("❌ Plotly安装失败")
            return False
    
    # 2. 检查依赖
    missing = check_dependencies()
    if missing:
        print(f"\n⚠️ 发现缺失依赖: {', '.join(missing)}")
        if not install_missing_packages(missing):
            print("❌ 依赖安装失败")
            return False
    
    # 3. 优化配置
    optimize_plotly_config()
    create_cdn_fallback()
    optimize_data_processing()
    create_performance_test()
    
    print("\n" + "=" * 50)
    print("🎉 性能优化完成!")
    print("=" * 50)
    
    print("\n📋 优化内容:")
    print("✅ Plotly配置优化")
    print("✅ CDN备用方案")
    print("✅ 数据处理优化")
    print("✅ 性能测试脚本")
    
    print("\n💡 使用建议:")
    print("1. 重启服务器: python run.py")
    print("2. 运行性能测试: python test_performance.py")
    print("3. 检查浏览器控制台是否有错误")
    print("4. 使用现代浏览器（Chrome、Firefox、Edge）")
    
    return True

if __name__ == "__main__":
    try:
        success = main()
        if not success:
            sys.exit(1)
    except KeyboardInterrupt:
        print("\n\n⚠️ 用户中断优化")
    except Exception as e:
        print(f"\n❌ 优化过程出错: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
